// pages/my/orderlist/orderlist.js
import { axios } from '../../../utils/ajax.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navindex: 0,
    data:[],
    returndata:'',
    userid:'',
    token:'',
    page:1,
    next_page:'',
    canload: false, 
    //猜你喜欢数据
    goodsdata: [],
    //用户点击的待成团订单的拼团id
    groupid:'',
    //用于拼团分享的图片链接
    shareimg:'',
    //swiper默认选中的index
    swiperindex:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let { userid = '', token = '' } = wx.getStorageSync('userinfo') 
    this.setData({
      navindex: parseInt(options.type),
      userid:userid,
      token: token,
      swiperindex:( parseInt(options.type) == 4 || parseInt(options.type) == 5 )? 1.5: 0
    })
    this.getdata()

    //读取猜你喜欢数据
    // axios({
    //   url: '/goods/guessLike'
    // }).then((res)=>{
    //   console.log(res)
    //   this.setData({
    //     goodsdata: res.data.goodslist
    //   })
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let page = this.data.page
    let next_page = this.data.next_page
    //如果有下一页
    if (next_page){
      page++
      this.setData({
        page: page
      })
      this.getdata(true)
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      let groupid = res.target.dataset.groupid
      let index = res.target.dataset.index
      console.log(groupid, index)
      console.log(this.data.data[index].goodsList[0].imgUrl)
      this.setData({
        groupid: groupid,
        shareimg: this.data.data[index].goodsList[0].imgUrl
      })
      return {
        title: '【仅剩' + this.data.data[index].surplusQuota + '个名额】我' + this.data.data[index].groupPrice+'元拼了' + this.data.data[index].goodsList[0].goodsName,
        path: `pages/home/goodsDetail/grouppage/grouppage?groupId=${this.data.groupid}`,
        imageUrl: this.data.shareimg
      }
    }
  },
  //导航切换
  choosenav (e) {
    let index = parseInt(e.currentTarget.dataset.index)
    //清空数据
    this.setData({
      navindex: index,
      data: [],
      returndata: '',
      page:1,
      canload: false
    })
    this.getdata()
  },
  //去订单详情
  goorderdetail (e){
    let orderid = e.currentTarget.dataset.orderid
    let orderno = e.currentTarget.dataset.orderno
    console.log(orderid, orderno)
    wx.navigateTo({
      url: `orderdetail/orderdetail?orderno=${orderno}&orderid=${orderid}`,
    })
  },
  //去退货详情页
  goreturndetail (e) {
    let returno = e.currentTarget.dataset.returno
    console.log(returno)
    wx.navigateTo({
      url: `returndetail/returndetail?returno=${returno}`,
    })
  },
  //请求数据
  getdata(loadmore=false) {
    let type = this.data.navindex
    //退货入口
    if (type==5){
      this.getreturndata(loadmore)
    //全部订单
    }else{
      this.getotherdata(loadmore)
    }
  },
  //获取退货数据
  getreturndata(loadmore = false) {
    let { userid = '', token = '' } = wx.getStorageSync('userinfo')
    axios({
      url: '/returnGoods/returnGoodsList',
      data: {
        userid: userid,
        token: token,
        page: this.data.page
      }
    }).then((res) => {
      console.log(res)
      // 加载更多数据
      if (loadmore) {
        this.setData({
          returndata: this.data.returndata.concat(res.data.goodsList)
        })
      } else {
        this.setData({
          returndata: res.data.goodsList
        })
      }
      this.setData({
        next_page: res.data.nextPage
      })
      if (this.data.next_page){
        this.setData({
          canload:true
        })
      }else{
        this.setData({
          canload: false
        }) 
      }
    })
  },
  //获取其余状态数据
  getotherdata (loadmore = false) {
    let type = this.data.navindex
    console.log(type)
    axios({
      url: '/order/orderList',
      data: {
        userid: this.data.userid,
        token: this.data.token,
        type: type,
        page: this.data.page
      }
    }).then((res) => {
      console.log(res.data.orderList)
      let newdata = res.data.orderList?res.data.orderList:[]
      if (newdata.length){
        newdata.forEach((v, i) => {
          v.goodsList.forEach((val, index) => {
            //只要有一条可售  那就显示重新购买的按钮
            if (val.isSale == 1) {
              v.showbuyagain = true
            }
          })
        })
      }
      //全部订单 加载更多数据
      if (loadmore && type ==1){
        this.setData({
          data: this.data.data.concat(newdata)
        })
      }else{
        this.setData({
          data: newdata
        })
      }
      console.log(this.data.data)
      this.setData({
        next_page: res.data.next_page
      })
      console.log(this.data.next_page)
      if (this.data.next_page) {
        this.setData({
          canload: true
        })
      } else {
        this.setData({
          canload: false
        })
      }
    })
  },
  //删除订单
  deleteorder (e) {
    wx.showModal({
      content: '确定要删除订单吗',
      success: (res)=> {
        if (res.confirm) {
          console.log('用户点击确定')
          let orderno = e.currentTarget.dataset.orderno
          console.log(orderno)
          axios({
            url: '/order/del',
            data: {
              userid: this.data.userid,
              token: this.data.token,
              orderNo: orderno
            }
          }).then((res)=>{
            console.log(res)
            let data = this.data.data
            data = data.filter(x => x.orderNo !== orderno)
            this.setData({
              data: data
            })
          })
        }
      }
    })
  },
  //取消订单
  cancelorder (e) {
    wx.showModal({
      content: '确定要取消订单吗',
      success:  (res)=> {
        if (res.confirm) {
          console.log('用户点击确定')
          let orderno = e.currentTarget.dataset.orderno
          console.log(orderno)
          axios({
            url: '/order/cancel',
            data: {
              userid: this.data.userid,
              token: this.data.token,
              orderNo: orderno
            }
          }).then((res) => {
            console.log(res)
            let data = this.data.data
            data = data.filter(x => x.orderNo !== orderno)
            this.setData({
              data: data
            })
          })
        }
      }
    })
  },
  //重新购买数据插入到购物车缓存 去购物车页面
  buyagain (e){
    let orderno = e.currentTarget.dataset.orderno
    console.log(orderno)
    //可以重新购买的订单数据
    let thisdata = this.data.data.find(x => x.orderNo == orderno).goodsList.filter(x => x.isSale==1)
    console.log(thisdata)
    //如果有商品有库存的话 走购物车
    if (thisdata.length){
      let obj = {}
      let specId = []
      let goodsId = []
      let num = []
      let goodsCheck = []
      for (let i = 0; i < thisdata.length ; i ++ ){
        num.push(1)
        goodsCheck.push(1)
      }
      obj = {
        "specId": thisdata.map(x => x.specId),
        "goodsId": thisdata.map(x => x.goodsId),
        "num": num,
        "goodsCheck": goodsCheck
      }
      console.log(obj)
      //获取购物车数据
      let cartGoods = wx.getStorageSync('cartGoods')
      console.log(cartGoods )
      //如果购物车有数据 那就在最前面插入数据
      if (cartGoods){
        let cartspecId = cartGoods.specId.split(',')
        let cartgoodsId = cartGoods.goodsId.split(',')
        let cartnum = cartGoods.num.split(',')
        let cartgoodsCheck = cartGoods.goodsCheck.split(',')
        for (let i = 0; i < thisdata.length; i++) {
          cartGoods.specId = cartspecId.unshift(obj.specId[i])
          cartGoods.goodsId = cartgoodsId.unshift(obj.goodsId[i])
          cartGoods.num = cartnum.unshift(obj.num[i])
          cartGoods.goodsCheck = cartgoodsCheck.unshift(obj.goodsCheck[i])
        } 
        cartGoods = {
          specId: cartspecId.join(),
          goodsId: cartgoodsId.join(),
          num: cartnum.join(),
          goodsCheck: cartgoodsCheck.join()
        }
      //否则直接push
      }else{
        cartGoods = {
          specId: obj.specId.join(),
          goodsId: obj.goodsId.join(),
          num: obj.num.join(),
          goodsCheck: obj.goodsCheck.join()
        }
      }
      console.log(cartGoods)
      wx.setStorageSync('cartGoods', cartGoods)
      wx.switchTab({
        url: '../../cart/cart',
      })
    }
  },
  //微信支付 直接走支付
  wxpay (e){
    let orderno = e.currentTarget.dataset.orderno
    console.log(orderno)
    axios({
      url: '/pay/wxpay',
      data: {
        userid: this.data.userid,
        token: this.data.token,
        orderNo:orderno
      }
    }).then((res)=>{
      console.log(res)
      wx.requestPayment({
        'timeStamp': res.data.timeStamp,
        'nonceStr': res.data.nonceStr,
        'package': res.data.package,
        'signType': res.data.signType,
        'paySign': res.data.paySign,
        'success': function (res) {
        },
        'fail': function (res) {
        }
      })
    })
  },
  //逛一逛
  gohome () {
    wx.switchTab({
      url: '../../home/home',
    })
  }
})